package com.spark.core;

import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("unchecked")
public class SparkServlet extends HttpServlet {
	
	private static final long serialVersionUID = -8843150247900658259L;
	
	private ServletConfig config;

	protected void initRequestAndResponse(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException{
		request.setCharacterEncoding(SparkConfiguration.DEFAULT_ENCODING);
		response.setCharacterEncoding(SparkConfiguration.DEFAULT_ENCODING);
		response.setContentType(SparkConfiguration.CONTENT_TYPE_HTML);
		response.addHeader("Access-Control-Allow-Origin", "http://localhost:8090");
	}
	
	
	protected XMap getParameterMap(HttpServletRequest request) throws Exception {
		Enumeration ep = request.getParameterNames();
		XMap params = new XMap();
		while (ep.hasMoreElements()) {
			String name = (String) ep.nextElement();
			String[] values = request.getParameterValues(name);
			if (values == null)
				params.put(name, null);
			else {
				if (values.length == 1) {
					if(SparkContext.REQUEST_DATA.equalsIgnoreCase(name)){
						if(values[0]!=null){
							Map data = (Map)JacksonMapper.getInstance().readValue(values[0], HashMap.class);
							params.put(name, data);
						}
					}else{
						params.put(name, values[0]);
					}					
				} else if (values.length > 1){
					params.put(name, values);
				}
			}
		}
		return params;
	}
	
	
	protected String getServicePath(HttpServletRequest request) {
		String url = request.getRequestURI();
		String sp = request.getServletPath();
		int index = url.indexOf(sp);
		if (index != -1) {
			return url.substring(index + sp.length(), url.length());
		}
		return null;
	}
	
	protected void initContext(SparkContext context, HttpServletRequest request, HttpServletResponse response) throws Exception{
		context.setServletConfig(this.config);
		context.setRequest(request);
		context.setResponse(response);
		context.setParameter(getParameterMap(request));
		context.setContextPath(request.getContextPath());
		context.setUserAgent(request.getHeader("User-Agent"));
		context.initSession();
		
//		context.put(SparkContext.SPARK_REQUEST, getParameterMap(request));
//		context.put(SparkContext.CONTEXT_PATH, request.getContextPath());
//		context.put(SparkContext.USER_AGENT, request.getHeader("User-Agent"));
	}
	
	public void init(ServletConfig config) throws ServletException {
		this.config = config;
	}
}
